import appEnum from "./appEnum";
import { getModules } from "./arcgisAPI";
import store from "./store";
// 创建图层
export async function createLayer(data: any) {
  try {
    const win: any = window;
    let layer = null;
    const options: any = {
      url: data.mapLayer.serviceUrl,
      outFields: ["*"],
      spatialReference: store.spatialReference
    };
    const Layer = await getLayerModule(data);
    switch (data.layerType) {
      case appEnum.layerType.MapImageLayer:
        const index = data.mapLayer.serviceUrl.lastIndexOf("/");
        const id = data.mapLayer.serviceUrl.substring(
          index + 1,
          data.mapLayer.serviceUrl.length
        );
        if (!isNaN(parseInt(id))) {
          layer = new Layer({
            url: data.mapLayer.serviceUrl.substring(0, index),
            sublayers: [
              {
                id: parseInt(id),
                visible: true
              }
            ]
          });
        } else {
          layer = new Layer({
            url: data.mapLayer.serviceUrl
          });
        }
        break;
      case appEnum.layerType.TileLayer:
        options.version = 10.5;
        layer = new Layer(options);
        break;
      case appEnum.layerType.WebTileLayer:
        if (store.constraint && win.webTileLayerFlag) {
          // eslint-disable-next-line no-eval
          const spatialReference = store.spatialReference;
          const constraint: any = store.constraint;
          const tileInfo = {
            dpi: 90.71428571427429,
            rows: 256,
            cols: 256,
            compressionQuality: 0,
            origin: {
              x: -180,
              y: 90
            },
            spatialReference,
            lods: constraint ? constraint.lods : []
          };
          layer = new Layer({
            urlTemplate: data.mapLayer.serviceUrl,
            tileInfo,
            spatialReference: tileInfo.spatialReference,
            fullExtent: {
              xmin: -180,
              ymin: -90,
              xmax: 180,
              ymax: 90,
              spatialReference
            },
            getTileUrl(level: any, row: any, col: any) {
              return this.urlTemplate
                .replace("{level}", length === 10 ? level : level + 1)
                .replace("{row}", row)
                .replace("{col}", col);
            }
          });
        } else if (win.webTileLayerFlag) {
          layer = new Layer({
            urlTemplate: data.mapLayer.serviceUrl,
            getTileUrl(level: any, row: any, col: any) {
              return this.urlTemplate
                .replace("{level}", length === 10 ? level : level + 1)
                .replace("{row}", row)
                .replace("{col}", col);
            }
          });
        } else {
          layer = new Layer({
            urlTemplate: data.mapLayer.serviceUrl
          });
        }
        break;
      case appEnum.layerType.FeatureLayer:
        options.elevationInfo = { mode: "relative-to-scene" };
        layer = new Layer(options);
        console.log(layer);
        break;
      default:
        layer = new Layer(options);
        break;
    }
    layer.serverUrl = data.mapLayer.serviceUrl;
    layer.id = data.mapLayer.id;
    layer.nodeId = data.nodeId ? data.nodeId : "";
    layer.title = data.displayName;
    layer.opacity = data.opacity / 100;
    layer.visible = data.checked;
    layer.labelsVisible = data.labelEnabled;
    layer.dataType = data.layerType;
    layer.parentName = data.parentName ? data.parentName : "";
    layer.categoryId = data.categoryId ? data.categoryId : "";
    return layer;
  } catch (error) {
    console.log(error);
    return null;
  }
}

export async function getLayerModule(data: any): Promise<any> {
  let module: any = null;
  switch (data.layerType) {
    case appEnum.layerType.SceneLayer:
      [module] = await getModules(["esri/layers/SceneLayer"]);
      break;
    case appEnum.layerType.FeatureLayer:
      [module] = await getModules(["esri/layers/FeatureLayer"]);
      break;
    case appEnum.layerType.ElevationLayer:
      [module] = await getModules(["esri/layers/ElevationLayer"]);
      break;
    case appEnum.layerType.MapImageLayer:
      [module] = await getModules(["esri/layers/MapImageLayer"]);
      break;
    case appEnum.layerType.TileLayer:
      [module] = await getModules(["esri/layers/TileLayer"]);
      break;
    case appEnum.layerType.IntegratedMeshLayer:
      [module] = await getModules(["esri/layers/IntegratedMeshLayer"]);
      break;
    case appEnum.layerType.BuildingSceneLayer:
      [module] = await getModules(["esri/layers/BuildingSceneLayer"]);
      break;
    case appEnum.layerType.WebTileLayer:
      [module] = await getModules(["esri/layers/WebTileLayer"]);
      break;
    case appEnum.layerType.ImageryTileLayer:
      [module] = await getModules(["esri/layers/ImageryTileLayer"]);
      break;
    case appEnum.layerType.WMTSLayer:
      [module] = await getModules(["esri/layers/WMTSLayer"]);
      break;
    case appEnum.layerType.WMSLayer:
      [module] = await getModules(["esri/layers/WMSLayer"]);
      break;
    case appEnum.layerType.ImageryLayer:
      [module] = await getModules(["esri/layers/ImageryLayer"]);
      break;
    case appEnum.layerType.WFSLayer:
      [module] = await getModules(["esri/layers/WFSLayer"]);
      break;
  }
  return module;
}

export const setFilter = ({
  layer,
  where,
  geometry,
  view
}: {
  layer: any;
  where?: string;
  geometry?: any;
  view: any;
}) => {
  const type = layer.type;
  switch (type) {
    case "map-image":
      return setMapLayerFilter(layer, where);
      break;
    case "feature":
      return setFeatureLayerFilter({ layer, where, geometry, view });
      break;
    default:
      return {
        status: false,
        msg: `仅支持MapImage和feature类型的图层，当前类型${type}不支持`
      };
      break;
  }
};

const setFeatureLayerFilter = ({
  layer,
  where,
  geometry,
  view
}: {
  layer: any;
  where?: string;
  geometry?: any;
  view: any;
}) => {
  view.whenLayerView(layer).then((layerView: any) => {
    const filter: any = {};
    where && (filter.where = where);
    geometry && (filter.geometry = geometry);
    layerView.filter = filter;
  });
  return { status: true, msg: `过滤图层${layer.title}` };
};

const setMapLayerFilter = (layer: any, where: string = "1=1") => {
  const subLayers = layer.sublayers;
  subLayers.forEach((el: any) => {
    el.definitionExpression = where;
  });
  return { status: true, msg: `根据${where}过滤图层${layer.title}` };
};
